package org.btik.lightweb.client;



import org.btik.light.meta.event.cmd.DefaultCmd;
import org.btik.light.server.platform.common.api.service.OperationServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Objects;

/**
 * @author lustre
 * @version 1.0
 * date 2021/5/15 12:37
 * web的Controller
 */
@RestController
public class DevControl {

    @Autowired
    private OperationServer manageServer;

    @RequestMapping("/url/control")
    public String led(String sn, String op, String... p) {
        System.out.println(sn + " " + op + " p " + Arrays.toString(p));
        if (sn != null) {
            if (manageServer.isOnLine(sn)) {
                int opCode;
                try {
                    opCode = Integer.parseInt(op);
                } catch (Exception e) {
                    return "opCode error!";
                }

                DefaultCmd webCmd = new DefaultCmd();
                webCmd.setTarget(sn);
                webCmd.setOpcode(opCode);
                if (Objects.nonNull(p)) {
                    ArrayList<String> params = new ArrayList<>(Arrays.asList(p));
                    webCmd.setParams(params);
                }
                manageServer.sendCmdOrMsg(webCmd);
                return "ok";
            }
        }

        return "do nothing";
    }
}
